<template>
  <!-- 导航栏 -->
  <NavbarComponent></NavbarComponent>
  <div class="container">
    <!-- 数量选择对话框 -->
    <el-dialog
      v-model="showQuantityDialog"
      title="选择数量"
      width="400px"
      :close-on-click-modal="false"
    >
      <div class="quantity-dialog">
        <div class="dialog-content">
          <span class="label">购买数量：</span>
          <el-input-number 
            v-model="selectedQuantity"
            :min="1"
            :max="product.count || 1"
            size="large"
            controls-position="right"
          />
          <span class="stock">库存 {{ product.count || 0 }} 件</span>
        </div>
        <div class="dialog-footer">
          <el-button @click="showQuantityDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmAddToCart">确认加入</el-button>
        </div>
      </div>
    </el-dialog>
    <!-- 图片放大弹窗 -->
 <!-- 修改后的图片弹窗 -->
 <div class="lightbox" v-if="lightboxVisible" @click.self="closeLightbox">
    <div class="lightbox-container">
      <el-carousel 
        :initial-index="activeIndex"
        arrow="always"
        height="70vh"
        class="lightbox-carousel"
      >
        <el-carousel-item 
          v-for="(img, index) in images" 
          :key="index"
          class="lightbox-item"
        >
          <img 
            :src="'http://localhost:8092' + img" 
            class="zoomed-image"
          />
        </el-carousel-item>
      </el-carousel>
      <button class="close-btn" @click="closeLightbox">
        <el-icon><Close /></el-icon>
      </button>
    </div>
  </div>

    <!-- 商品主内容区 -->
    <div class="main-content">
      <!-- 商品图片 -->
     <!-- 修改后的商品图片区域 -->
     <div class="product-image" @click="openLightbox">
    <el-carousel 
      :autoplay="images.length > 1 ? 3000 : false"
      indicator-position="outside"
      arrow="always"
      height="480px"
      ref="carousel"
    >
      <el-carousel-item 
        v-for="(img, index) in images" 
        :key="index"
        class="carousel-item"
      >
        <div class="image-container">
          <img 
            :src="'http://localhost:8092' + img" 
            :alt="product.productName"
            class="main-image"
          />
          <div class="hover-effect">
            <el-icon class="zoom-icon"><ZoomIn /></el-icon>
            <div class="zoom-text">点击查看大图</div>
          </div>
        </div>
      </el-carousel-item>
    </el-carousel>
  </div>

      <!-- 商品详情 -->
      <div class="product-info">
        <!-- 卖家信息 -->
        <div class="seller-card" v-if="userInfo.userId">
          <div class="seller-header">
            <img :src="'http://localhost:8092' + userInfo.avatar" class="seller-avatar" alt="卖家头像" />
            <div class="seller-info">
              <div class="seller-name">{{ userInfo.nickname || '未知用户' }}</div>
              <div class="seller-major">{{ userInfo.major || '未填写专业信息' }}</div>
            </div>
            <div class="credit-info">
              <el-tooltip effect="dark" content="根据交易行为计算的信用评分" placement="top">
                <div class="credit-badge" :class="creditClass">
                  <span class="credit-score">{{ userInfo.credit || 0 }}</span>
                  <div class="credit-label">{{ creditText }}</div>
                </div>
              </el-tooltip>
            </div>
          </div>
          <el-button class="contact-btn" type="primary" size="large" @click="goToChatPage">
            <i class="iconfont icon-message"></i> 联系卖家
          </el-button>
        </div>

        <!-- 商品基本信息 -->
        <h1 class="product-title">{{ product.productName }}</h1>
        <div class="meta">
          <el-tag type="info" size="small">浏览 {{ product.click || 0 }}次</el-tag>
          <el-tag type="info" size="small" style="margin-left: 8px">库存 {{ product.count || 0 }}件</el-tag>
        </div>

        <!-- 价格信息 -->
        <div class="price-box">
          <span class="price-label">售价</span>
          <span class="price">¥{{ product.price }}</span>
          <span class="original-price" v-if="product.originalPrice">¥{{ product.originalPrice }}</span>
        </div>

        <!-- 商品描述 -->
        <div class="product-desc">
          <h3 class="desc-title">商品详情</h3>
          <pre class="desc-content">{{ product.introduction }}</pre>
        </div>

        <!-- 购买按钮 -->
        <div class="action-buttons">
          <el-button 
      class="add-to-cart" 
      type="warning" 
      size="large" 
      @click="showAddCartDialog"
    >
      <el-icon><Plus /></el-icon>加入购物车
    </el-button>
          <el-button class="buy-now" type="danger" size="large" @click="handleBuyNow">
            <el-icon><Shop /></el-icon>立即购买
          </el-button>
        </div>
      </div>
    </div>

    <!-- 用户评价 -->
    <div class="review-section" >
  <div class="section-header">
    <div class="title-container">
      <span class="decorative-line"></span>
      <h2 class="section-title">
        用户评价
        <span class="review-count">{{ reviews.length }}</span>
      </h2>
      <span class="decorative-line"></span>
    </div>
    <div class="subtitle">已购用户真实反馈</div>
  </div>
      <div class="review-list" v-if="reviews.length > 0">
        <div v-for="review in reviews" :key="review.orderId" class="review-item">
          <div class="user-info">
            <img :src="'http://localhost:8092' + review.avatar" class="user-avatar" />
            <div class="user-meta">
              <div class="user-name">{{ review.nickname }}</div>
              <div class="review-time">{{ formatDate(review.updatedAt) }}</div>
            </div>
          </div>
          <div class="review-content">
            <el-rate
              v-model="review.stars"
              disabled
              :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
              void-color="#EFF2F7"
              allow-half
            />
            <pre class="evaluation-text">{{ review.evaluation }}</pre>
          </div>
        </div>
      </div>
      <div v-else class="no-reviews">
      <el-empty description="暂无用户评价，快来购买并评价~" />
    </div>
    </div>

    
  </div>
</template>


<script setup>
import { ref, onMounted,computed } from 'vue';
import NavbarComponent from "@/components/components/NavbarComponent.vue";
import { useRoute ,useRouter} from 'vue-router';
import { Plus ,Shop} from '@element-plus/icons-vue';
import axios from 'axios';
import { ElMessage ,ElMessageBox} from 'element-plus';

const product = ref({});
const userInfo = ref({});
const route = useRoute();
const lightboxVisible = ref(false);
const router = useRouter()
const reviews = ref([])
const showQuantityDialog = ref(false);
const selectedQuantity = ref(1);
// 图片放大控制
// const openLightbox = () => {
//   lightboxVisible.value = true;
//   document.body.style.overflow = 'hidden';
// };
const images = computed(() => {
  return product.value.images ? 
    product.value.images.split(',').map(img => img.trim()) : 
    [];
});

const activeIndex = ref(0);
const carousel = ref(null);
// 图片放大控制
const openLightbox = () => {
  if (carousel.value) {
    activeIndex.value = carousel.value.setActiveItem();
  }
  lightboxVisible.value = true;
  document.body.style.overflow = 'hidden';
};
const closeLightbox = () => {
  lightboxVisible.value = false;
  document.body.style.overflow = '';
};

// 数据获取
onMounted(async () => {
  const productId = route.query.productId;
  if (productId) {
    await fetchProductDetail(productId);
    await fetchReviews(productId); 
    if (product.value.userId) {
      await fetchUserDetail(product.value.userId);
    }
  }
});

const fetchProductDetail = async (productId) => {
  try {
    const { data } = await axios.get(`http://localhost:8092/product/getDetail`, {
      params: { 
        productIds: [productId].join(',') // 转换为数组并序列化
      }
    });
    product.value = Array.isArray(data.data) && data.data.length > 0 ? data.data[0] : {};
  } catch (error) {
    console.error("商品加载失败", error);
  }
};
//获取商家电话和email 
const goToChatPage = () => {
  const sellerPhone = userInfo.value.phone || '未提供'
  const sellerEmail = userInfo.value.email || '未提供'

  ElMessageBox.alert(
    `<div style="line-height: 1.6;">
      <p style="margin: 12px 0;"><strong>联系电话：</strong>${sellerPhone}</p>
      <p style="margin: 12px 0;"><strong>联系邮箱：</strong>${sellerEmail}</p>
    </div>`,
    '商家联系方式',
    {
      confirmButtonText: '确定',
      dangerouslyUseHTMLString: true,
      customClass: 'contact-message-box'
    }
  )
}
//获取卖家信息
const fetchUserDetail = async (userId) => {
  try {
    const { data } = await axios.get(`http://localhost:8092/user/getUserDetailById`, {
      params: { userId }
    });
    userInfo.value = Array.isArray(data.data) && data.data.length > 0 ? data.data[0] : {};
  } catch (error) {
    console.error("用户信息加载失败", error);
  }
};
const showAddCartDialog = () => {
  const token = localStorage.getItem('token');
  if (!token) {
    ElMessage.error('请先登录');
    return router.push('/login');
  }
  selectedQuantity.value = 1;
  showQuantityDialog.value = true;
};

const confirmAddToCart = async () => {
  try {
    if (selectedQuantity.value < 1) {
      ElMessage.error('数量不能小于1');
      return;
    }
    if (selectedQuantity.value > product.value.count) {
      ElMessage.error(`库存不足，剩余${product.value.count}件`);
      return;
    }

    const { data } = await axios.post('http://localhost:8092/cart/add', {
      productId: product.value.productId,
      quantity: selectedQuantity.value
    }, {
      headers: {
        Authorization: `Bearer ${localStorage.getItem('token')}`
      }
    });

    if (data.code === 200) {
      ElMessage.success({
        message: `成功添加${selectedQuantity.value}件到购物车`,
        duration: 2000
      });
      showQuantityDialog.value = false;
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.msg || '添加失败');
  }
};
const handleBuyNow = () => {
  
  if (product.value.productId) {
    router.push({
      path: '/buy',
      query: {
        productIds: product.value.productId,
        userId: product.value.userId, //卖家id
        // 可以携带更多参数（可选）
        quantity: 1 ,// 默认购买数量，
        isSingle:1 ,// 是否单独购买
        price:product.value.price // 单价
      }
    })
  } else {
    ElMessage.error('商品信息加载失败，请稍后重试')
  }
}

//获取评论数据
const fetchReviews = async (productId) => {
  try {
    const { data } = await axios.get('http://localhost:8092/order/getReviewsByProductId', {
      params: { productId }
    })
    if (data.code === 200) {
      reviews.value = data.data
    }
  } catch (error) {
    console.error('获取评价失败:', error)
  }
}

// 新增时间格式化方法
const formatDate = (timestamp) => {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  }) + ' ' + date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}
// 新增计算属性
const creditText = computed(() => {
  const credit = userInfo.value.credit || 0
  if (credit >= 300) return '极好'
  if (credit >= 200) return '较好'
  if (credit >= 100) return '一般'
  return '极差'
})

const creditClass = computed(() => {
  const credit = userInfo.value.credit || 0
  return {
    'credit-excellent': credit >= 300,
    'credit-good': credit >= 200 && credit < 300,
    'credit-normal': credit >= 100 && credit < 200,
    'credit-poor': credit < 100
  }
})
</script>

<style lang="scss" scoped>
/* 容器布局 */
.container {
  max-width: 1440px;
  margin: 32px auto;
  padding: 0 48px;
}

.main-content {
  display: flex;
  gap: 64px;
  margin-bottom: 80px;
}

/* 商品轮播图样式 */
.product-image {
  flex: 0 0 720px;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.08);
  position: relative;

  :deep(.el-carousel) {
    border-radius: 16px;
    height: 480px;

    .el-carousel__container {
      height: 480px !important;
      position: relative;
    }

    .el-carousel__arrow {
      width: 48px;
      height: 48px;
      background: rgba(255, 255, 255, 0.3);
      backdrop-filter: blur(4px);
      transition: all 0.3s cubic-bezier(0.23, 1, 0.32, 1);
      
      &:hover {
        background: rgba(255, 255, 255, 0.5);
        transform: scale(1.1);
      }
      
      i {
        font-size: 24px;
        color: rgba(0, 0, 0, 0.8);
      }
    }

    .el-carousel__indicators {
      padding: 0 0 20px 0;
      
      .el-carousel__indicator {
        padding: 12px 4px;
        
        .el-carousel__button {
          width: 24px;
          height: 4px;
          border-radius: 2px;
          background: rgba(255, 255, 255, 0.5);
          transition: all 0.3s ease;
        }
        
        &.is-active .el-carousel__button {
          width: 32px;
          background: rgba(255, 255, 255, 0.9);
        }
      }
    }
  }

  .image-container {
    width: 100%;
    height: 100%;
    position: relative;
    overflow: hidden;

    .main-image {
      width: 100%;
      height: 100%;
      object-fit: cover;
      transition: transform 0.3s cubic-bezier(0.23, 1, 0.32, 1);
    }

    &:hover {
      .main-image {
        transform: scale(1.03);
      }
      .hover-effect {
        opacity: 1;
      }
    }
  }
}

/* 悬停放大提示 */
.hover-effect {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  opacity: 0;
  transition: opacity 0.3s ease;
  pointer-events: none;

  .zoom-icon {
    font-size: 40px;
    color: rgba(255, 255, 255, 0.9);
    filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.2));
    margin-bottom: 12px;
  }

  .zoom-text {
    color: white;
    font-size: 16px;
    font-weight: 500;
    text-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
    white-space: nowrap;
  }
}

/* 商品信息区域 */
.product-info {
  flex: 1;
  min-width: 520px;
}

/* 卖家信息卡片 */
.seller-card {
  background: #ffffff;
  border-radius: 16px;
  padding: 32px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.06);
  margin-bottom: 40px;

  .seller-header {
    display: flex;
    align-items: center;
    margin-bottom: 24px;

    .seller-avatar {
      width: 88px;
      height: 88px;
      border-radius: 50%;
      margin-right: 20px;
      border: 3px solid #fff;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
    }

    .seller-info {
      flex: 1;
      
      .seller-name {
        font-size: 20px;
        font-weight: 700;
        color: #1a1a1a;
        margin-bottom: 6px;
        letter-spacing: 0.5px;
      }
      
      .seller-major {
        font-size: 15px;
        color: #666;
        opacity: 0.9;
      }
    }
  }
}

/* 信用评分徽章 */
.credit-badge {
  width: 96px;
  height: 96px;
  border-radius: 12px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  
  .credit-score {
    font-size: 28px;
    font-weight: 800;
    line-height: 1;
  }
  
  .credit-label {
    font-size: 13px;
    margin-top: 6px;
    letter-spacing: 0.5px;
  }
  
  &.credit-excellent { 
    background: linear-gradient(135deg, #a8e063 0%, #56ab2f 100%);
    color: #fff;
  }
  &.credit-good { 
    background: linear-gradient(135deg, #ffd200 0%, #f7971e 100%);
    color: #fff;
  }
  &.credit-normal { 
    background: linear-gradient(135deg, #ff9a9e 0%, #fad0c4 100%);
  }
  &.credit-poor { 
    background: linear-gradient(135deg, #ff6b6b 0%, #ff8787 100%);
    color: #fff;
  }
}

/* 联系按钮 */
.contact-btn {
  width: 100%;
  height: 56px;
  font-size: 17px;
  border-radius: 12px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  letter-spacing: 0.5px;
  transition: all 0.3s cubic-bezier(0.23, 1, 0.32, 1);
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(118, 75, 162, 0.25);
  }
}

/* 商品标题 */
.product-title {
  font-size: 36px;
  font-weight: 800;
  color: #1a1a1a;
  margin: 0 0 20px;
  line-height: 1.3;
  letter-spacing: -0.5px;
}

/* 商品元信息 */
.meta {
  margin-bottom: 28px;
  
  .el-tag {
    border-radius: 8px;
    font-weight: 600;
    padding: 8px 16px;
    font-size: 14px;
  }
}

/* 价格区域 */
.price-box {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 28px;
  margin-bottom: 40px;
  
  .price-label {
    font-size: 16px;
    color: #666;
    margin-right: 10px;
    letter-spacing: 0.5px;
  }
  
  .price {
    font-size: 48px;
    font-weight: 900;
    color: #ff4d4f;
    margin-right: 16px;
    letter-spacing: -1px;
  }
  
  .original-price {
    font-size: 20px;
    color: #999;
    text-decoration: line-through;
    vertical-align: text-bottom;
  }
}

/* 商品描述 */
.product-desc {
  background: #fff;
  border-radius: 16px;
  padding: 36px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.06);
  
  .desc-title {
    font-size: 24px;
    font-weight: 700;
    color: #1a1a1a;
    margin: 0 0 24px;
    letter-spacing: -0.5px;
  }
  
  .desc-content {
    font-size: 17px;
    line-height: 1.8;
    color: #4a4a4a;
    white-space: pre-wrap;
    font-family: inherit;
    letter-spacing: 0.3px;
  }
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  gap: 24px;
  margin-top: 48px;
  
  .el-button {
    flex: 1;
    height: 64px;
    font-size: 18px;
    border-radius: 16px;
    transition: all 0.3s cubic-bezier(0.23, 1, 0.32, 1);
    letter-spacing: 0.5px;
    
    &:hover {
      transform: translateY(-3px);
      box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
    }
    
    &.add-to-cart {
      background: linear-gradient(135deg, #ffd700 0%, #ffb347 100%);
      border: none;
    }
    
    &.buy-now {
      background: linear-gradient(135deg, #ff6b6b 0%, #ff8e8e 100%);
      border: none;
    }
  }
}

/* 用户评价区域 */
.review-section {
  background: #fff;
  border-radius: 16px;
  padding: 48px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.06);
  margin-bottom: 64px;
  
  .section-header {
    text-align: center;
    margin-bottom: 48px;

    .title-container {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 32px;
      margin-bottom: 16px;
    }

    .decorative-line {
      width: 80px;
      height: 3px;
      background: linear-gradient(90deg, transparent, #409EFF, transparent);
    }

    .section-title {
      font-size: 28px;
      color: #303133;
      margin: 0;
      display: flex;
      align-items: center;
      gap: 12px;
      font-weight: 700;

      .review-count {
        color: #ff5500;
        font-size: 32px;
        font-weight: 800;
      }
    }

    .subtitle {
      color: #909399;
      font-size: 15px;
      letter-spacing: 0.5px;
      margin-top: 8px;
    }
  }
}

/* 评价项 */
.review-item {
  display: flex;
  gap: 28px;
  padding: 32px;
  background: #f8f9fa;
  border-radius: 12px;
  margin-bottom: 24px;
  transition: transform 0.3s cubic-bezier(0.23, 1, 0.32, 1);
  
  &:hover {
    transform: translateX(10px);
  }

  .user-avatar {
    width: 64px;
    height: 64px;
    border-radius: 50%;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
  }

  .review-content {
    flex: 1;
    
    .evaluation-text {
      font-size: 16px;
      line-height: 1.8;
      color: #4a4a4a;
      margin-top: 16px;
      letter-spacing: 0.3px;
    }
  }
}

/* 无评价提示 */
.no-reviews {
  margin: 80px 0;
  background: #f8f9fa;
  border-radius: 16px;
  padding: 80px 0;
  
  ::v-deep .el-empty__description p {
    color: #909399;
    font-size: 16px;
    letter-spacing: 0.3px;
  }
}

/* 大图弹窗 */
.lightbox {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.96);
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
  backdrop-filter: blur(16px);
  animation: lightboxFadeIn 0.4s cubic-bezier(0.23, 1, 0.32, 1);

  .lightbox-container {
    width: 80vw;
    max-width: 1200px;
    position: relative;

    :deep(.lightbox-carousel) {
      .el-carousel__container {
        height: 70vh !important;
      }
      
      .el-carousel__arrow {
        background: rgba(255, 255, 255, 0.15);
        transition: all 0.3s ease;
        
        &:hover {
          background: rgba(255, 255, 255, 0.25);
        }
        
        i {
          font-size: 24px;
        }
      }
      
      .el-carousel__indicators {
        bottom: -40px;
      }
    }

    .zoomed-image {
      width: 100%;
      height: 100%;
      object-fit: contain;
      border-radius: 8px;
    }
  }
}

/* 关闭按钮 */
.close-btn {
  position: absolute;
  top: 32px;
  right: 32px;
  width: 56px;
  height: 56px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.15);
  border: none;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s cubic-bezier(0.23, 1, 0.32, 1);
  
  &:hover {
    background: rgba(255, 255, 255, 0.25);
    transform: rotate(90deg) scale(1.1);
  }

  .el-icon {
    font-size: 24px;
    color: white;
  }
}

/* 动画 */
@keyframes lightboxFadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

@keyframes imageZoomIn {
  from {
    transform: scale(0.95) translateY(24px);
    opacity: 0;
  }
  to {
    transform: scale(1) translateY(0);
    opacity: 1;
  }
}

/* 数量选择对话框 */
.quantity-dialog {
  padding: 32px;
  
  .dialog-content {
    display: flex;
    align-items: center;
    gap: 24px;
    margin-bottom: 40px;

    .label {
      font-size: 17px;
      color: #606266;
      letter-spacing: 0.3px;
    }

    .stock {
      font-size: 15px;
      color: #999;
      margin-left: auto;
    }

    :deep(.el-input-number) {
      width: 140px;
      
      .el-input__inner {
        text-align: center;
        font-size: 16px;
        height: 48px;
      }
    }
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 20px;
    
    .el-button {
      padding: 12px 32px;
      font-size: 15px;
      border-radius: 12px;
    }
  }
}
.contact-message-box {
  width: 400px !important;
  border-radius: 12px !important;
  padding: 24px !important;
  
  .el-message-box__header {
    padding-bottom: 16px;
  }
  
  .el-message-box__title {
    font-size: 20px;
    font-weight: 600;
    color: #303133;
  }
  
  .el-message-box__content {
    font-size: 16px;
    color: #606266;
    padding: 16px 0;
  }
  
  .el-message-box__btns {
    padding-top: 24px;
  }
  
  .el-button {
    padding: 12px 32px;
    border-radius: 8px;
  }
}
</style>